<?php

namespace app\admin\controller;

use think\captcha\Captcha;
use think\Controller;

class Login extends Controller {
    /**
     * 登录页面
     * @return mixed
     */
    public function index(){
        if (!empty(get_user_id())){
            $this->redirect('admin/index/index');
        }

        $this->assign('login_captcha',get_system_val('login_captcha'));
        return $this->fetch();
    }

    public function captchaCode(){
        $config = [
            'useCurve' => false,
            'useNoise' => false
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }


    public function doLogin($username,$password,$captcha = ''){
        if (is_post()){
            $code = 0;
            $msg = '';
            $url = '';

            if (get_system_val('login_captcha') == 1 && !captcha_check($captcha)){
                $code = 2;
                $msg = '验证码错误';
            }elseif (empty($username)){
                $msg = '用户名不能为空';
            }elseif (empty($password)){
                $msg = '密码不能为空';
            }elseif (!empty($username) && !empty($password)){
                $user = db('user')
                    ->where('username', $username)
                    ->where('password', qa_encrtyp($password))
                    ->find();

                if ($user) {
                    if ($user['status'] == 1) {
                        $code = 1;
                        $msg = '登录成功';
                        $url = url('admin/index/index');
                        cookie('u_name', $user['username']);
                        session('name', $user['name']);
                        session('u_id', $user['id']);
                        insert_system_log('用户：' . $user['name'] . '，ID：' . $user['id'] . ' 登录系统');
                    } else {
                        $msg = '账号已禁用';
                    }
                } else {
                    $msg = '用户名或密码错误';
                }
            }

            return json(['code' => $code, 'msg' => $msg, 'url' => $url]);
        }
    }

    public function logout(){
        session('u_id',null);
        $this->redirect(url('admin/index/index'));
    }
}